<?php
namespace Lib\Controller;
use Home\Logic\WxloginLogic;

class AdminBaseController extends BaseController{

    private $wxLoginLogic;
    private $AccessTokenModel;
    public function __construct(){
        parent::__construct();
        $this->_init();

        $this->wxLoginLogic = new WxloginLogic();
        $this->AccessTokenModel = D('wx_access_token');
        if(cookie('wx_access_token')==null){
             $this->_getWXAccessToken();
        }

    }

    /**
     * 获取微信accessToken
     */
    private function _getWXAccessToken(){
        $findAccessToken = $this->AccessTokenModel->order('id desc')->find();
        if(!empty($findAccessToken) && $findAccessToken['expires_time'] < time() || empty($findAccessToken)){
            $this->wxLoginLogic->getAccessToken();

            $accessTokenData['wx_access_token'] = cookie("wx_access_token");
            $accessTokenData['create_time'] = time();
            $accessTokenData['expires_time'] = time()+7000;
            $addNewAccessToken = $this->AccessTokenModel->add($accessTokenData);
        }
        else if(!empty($findAccessToken) && $findAccessToken['expires_time'] > time()){
            $token['access_token'] = $findAccessToken['wx_access_token'];
            $expireTime = $findAccessToken['expires_time'] - time();
            cookie('wx_access_token',$token["access_token"],$expireTime);
        }
    }

    /**
     * 推送微信消息模板
     * @param array $userInfo 用户信息
     * @param array $pushdata 模板数据data
     * @param array $templateid 模板id
     * @param array $color 头标题颜色
     * @param array $data
     */
    public function pushWXMessage($userInfo,$pushdata,$templateid,$orderurl=''){

        $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".cookie('wx_access_token');

        //封装模板数据
        $pushdata = array(
            'touser' => $userInfo['weixin_openid'],
            'template_id' => $templateid,
            'url' => $orderurl,
            'topcolor' => '#FF0000', //红色
            'data' => $pushdata
        );


        $json_pushdata = json_encode($pushdata);

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, urldecode($json_pushdata));
        $output = curl_exec($ch);
        curl_close($ch);

        $pushResult = json_decode($output,true);
        if($pushResult['errcode'] == '-1'){
            $this->pushWXMessage($userInfo, $pushdata,$templateid,$orderurl='');
        }
    }

    private function _init(){
        // 验证登陆，检查用户id
        if (! session(C('USER_AUTH_KEY'))) {
            if (IS_AJAX) { // 登录超时，Ajax请求时跳转
                $this->error('登录超时', U(MODULE_NAME . '/Public/login', '', true, false, true, true));
            }
            redirect(U(MODULE_NAME . '/Public/login'));
        }
        $allMenuId = S('allMenuId');
        // 检查菜单缓存
        if (! $allMenuId) {
            $this->menuObj = M('Menu');
            $this->_cacheMenuList();
        }
//         return;
        // 获取当前地址
        $this->assign('breadcrumbs', $this->_getBreadcrumbs());
        // 注册菜单列表TODO：日后不属于该角色的菜单不显示出来
        $this->assign('menuList', arrayMerge(S('menuList')));
    }


    /**
     * 缓存菜单
     */
    private function _cacheMenuList() {
        //所有菜单的ID
        $allMenuId = array();
        //分配多权限管理员
        if(session('roleId')>=2){
            $where['role_id'] = session('roleId');
            $where['access_type'] = 2;
            $menuIdList = M('access')->where($where)->select();
            foreach($menuIdList as$w=>$menuId){
                $menuList[$w] = $this->menuObj->where(array('status' => 1,'id'=>$menuId['access_type_id']))->order('sort desc')->find();
                if($menuList[$w] == ''){
                    unset($menuList[$w]);
                }
            }
            $menuList = array_merge($menuList);
        }else{
            $menuList = $this->menuObj->where(array('status' => 1))->order('sort desc')->select();
        }
//         p(array_merge($menuList));
        //TODO：2017-10-27新增
        S('menuList', NULL);
        S('allMenuId', NULL);
        S('language', NULL);
        S('currency', NULL);
        S('oauths', NULL);
        S('sysConfig', NULL);
        S('jsCacheNum', NULL);
        S('categoryList',NULL);
        
        
//         $menuWhere['status'] = 1 ;
// //         if(session(C('USER_AUTH_KEY')) != -1){
// //             $menuWhere['_string'] = 'id != 42 and id != 38 and id != 48 and id != 1' ;
// //         }
//         $menuList = $this->menuObj->where($menuWhere)->order('sort desc')->select();
//         p($this->menuObj->getLastSql());
        foreach ($menuList as $key => $menu) {
            if (!empty($menu['name'])) {
                $allMenuId[$key] = $menu['id'];
            }
        }
//         p($menuList);
        //缓存所有菜单id
        S('allMenuId', $allMenuId);
        //缓存菜单列表
        S('menuList', $menuList);
    }

    /**
     * 获取当前位置
     * @return null
     */
    private function _getBreadcrumbs() {
        //菜单名
        $menuName = strtolower(CONTROLLER_NAME . '/' . ACTION_NAME);
        //获取所有菜单
        $menuList = S('menuList');
        //菜单key
        $i = NULL;
        foreach ($menuList as $key => $menu) {
            if (strtolower($menu['operation']) == $menuName) {
                $i = $key;
                break;
            }
        }
        if ($i >0) {
            //方法
            $action = $menuList[$i];
            $this->meniId = $action['id'];
            //记录菜单id
            if ($action['is_show']) {
                session('menuId', $action['id']);
            }
            foreach ($menuList as $menu) {
                if ($menu['id'] == $action['p_id']) {
                    //模块
                    $module = $menu;
                    break;
                }
            }
            //当前位置
            return "&nbsp;&nbsp;" . $module['name'] . "&nbsp;&nbsp;&gt;&nbsp;&nbsp;" . $action['name'];
        } else {
            //p(1);
            return null;
        }
    }


}

?>
